# coding:utf-8
import mock.views as mviews
import time
import json
import copy
from mock.models import MockLog
from api.tasks import interfaceTest1

requestError = '''{
    state_code: 404,
    err_msg: ' 短信router不存在！'
}'''


# Create your views here.
def sms(request, api=None, router=None):
    """
    短信服务统一入口
    :param request:
    :param api:
    :param router:
    :return:
    """
    # mviews.checkUrl(request, api, router)
    responseModel = mviews.getResponseData(api, router)  # 从数据库获取返回值模板
    delay = responseModel.delay
    modelJson = json.loads(responseModel.json)

    if router == 'lxt':
        responseData = creatLxtResponseData(request, modelJson)  # 组装返回数据联信通
        mviews.mockLog(api, router, responseData)
        time.sleep(delay)
        return mviews.createJSONResponse(responseData)
    elif router == 'mandao':
        pass
        return
    else:
        return mviews.createJSONResponse(requestError)


def creatLxtResponseData(request, modelJson):
    """
    根据请求和响应模板，组装返回值
    :param request:请求信息
    :param result:模板信息
    :return: json.dumps(result)
    """
    postBody = request.body
    requestBody = json.loads(postBody)
    i = 0
    mobileNum = len(requestBody["mobileNo"])
    for mobile in requestBody["mobileNo"]:
        modelJson['rets'][i]["mobile"] = mobile
        modelJson['rets'][i]["msgId"] = int(mobile) + int(time.time())
        a = copy.deepcopy(modelJson['rets'][0])
        if i < mobileNum - 1:
            modelJson['rets'].append(a)
            i = i + 1
    result = json.dumps(modelJson)
    return result


def lxtReport(request):
    postBody = json.loads(request.body)
    modelJson = postBody['model']
    posturl = postBody['url']
    maxNum = postBody['maxNum']
    LxtRequestDatas = creatLxtRequestData(modelJson, maxNum)
    for  LxtRequestData in  LxtRequestDatas:
        interfaceTest1()





def creatLxtRequestData(modelJson, maxNum=10):
    """
    根据状态，返回状态报告
    :param request:通过request请求，获取模板
    :param maxNum:状态报告一次返回的数据记录数
    :return:
    """

    RequestDatas = MockLog.objects.filter(apipath='sms', routerpath='lxt', status=True)[:maxNum]
    RequestDataResult = []
    i = 0
    for RequestData in RequestDatas:
        RequestData = json.loads(RequestData.json)
        while i < len(RequestData["rets"]):
            #modelJson["destId"] = RequestData['rets'][i]["mobile"]
            modelJson["mobile"] = RequestData['rets'][i]["mobile"]
            modelJson["msgId"] = RequestData['rets'][i]["msgId"]
            modelJson["reqId"] = int(RequestData['rets'][i]["mobile"]) + int(time.time())
            modelJson["status"] = False
            RequestDataResult.append(modelJson)
            i += 1
    RequestDataResult = json.dumps(RequestDataResult)
    return RequestDataResult
